import URLs from '@/config/url.js'

/**
 * 上传图片
 */
function uploadImage(count=1) {
	return new Promise((resolve, reject) => {
		uni.chooseImage({
			count,
			sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
			sourceType: ['album', 'camera'], //从相册选择
			success: function(res) {
				console.log(res)
				const tempFilePath = res.tempFilePaths;
				if(tempFilePath.length > 1){
					const promiseAll = []
					tempFilePath.forEach(item => {
						promiseAll.push(uploadFile(item))
					})
					Promise.all(promiseAll).then(res => {
						resolve(res)
					})
				}else{
					uploadFile(tempFilePath[0]).then(res => {
						resolve(res)
					})
				}
			}
		});
	})
}


/**
 * 上传文件
 */
function uploadFile(tempPath) {
	return new Promise((resolve, reject) => {
		uni.uploadFile({
			url: URLs.host + '/common/upload', //上传地址
			filePath: tempPath,
			name: 'file',
			formData: {
				"Content-Type": "multipart/form-data"
			},
			success: function(res) {
				var data = res.data;
				data = JSON.parse(data);
				resolve(data)
			},
			fail: function(err) {
				reject(err)
			}
		});
	})
}

export {
	uploadImage,
	uploadFile
}